package cn.tpshion.config.support;

import cn.tpshion.config.service.AuthService;
import cn.tpshion.config.service.impl.InMemoryAuthServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.Objects;

@Configuration
@Slf4j
public class ConfigMvc implements WebMvcConfigurer {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Value("${config.zookeeper.host}")
    private String host;

    /**
     * 注册认证拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login");
    }

    /**
     * 默认使用内存模式
     * @return
     */
    @Bean
    public AuthService authService(){
        return new InMemoryAuthServiceImpl();
    }

    /**
     * 创建zookeeper客户端实例
     * @return
     */
    @Bean(destroyMethod = "close")
    public CuratorFramework curatorFramework(){
        log.info("开始连接zookeeper，host:{}", this.host);
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                .connectString(this.host)
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("config")
                .build();
        zkClient.start();
        log.info("zookeeper连接成功");
        return zkClient;
    }

    /**
     * 销毁zookeeper客户端实例
     */
    public void close(){
        CuratorFramework curatorFramework = curatorFramework();
        if(Objects.nonNull(curatorFramework())){
            curatorFramework.close();
        }
    }

    @Bean
    public ServerEndpointExporter endpointExporter() {
        return new ServerEndpointExporter();
    }
}
